<script setup lang="ts">/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */

import {testGenerateBillSummary} from "@/api/billSummary";

defineOptions({
  name: "OrderImport",
  inheritAttrs: false,
});
import { UploadFile, ElLoading } from "element-plus";
import 'element-plus/theme-chalk/el-loading.css'
import {importBill} from "@/api/bill";
import {importColumn} from "@/api/columnImport";
import {getByStoreKey, listAll} from "@/api/store";
import {deleteData} from "@/api/dataDelete";

const queryFormRef = ref(ElForm); // 查询表单
const sourceRef = ref(ElForm);
const columnFormRef = ref(ElForm);
const omsFormRef = ref(ElForm);
import { StoreForm } from "@/api/store/types";
import { ImportVO } from "@/api/bill/types";
import { ColumnImportVO } from "@/api/columnImport/types";
import {DataParam} from "@/api/dataDelete/types";
import {importOmsData} from "@/api/omsOrder";
import lodash from "lodash-es";

const loading = ref(false);
const deleteMonthValue = ref('')
const deleteParams = reactive<DataParam>({
	month: ''
});

const importDialog = reactive<DialogOption>({
  title: "原始账单导入",
  visible: false,
});

const importColumnDialog = reactive<DialogOption>({
	title: "平台字段导入",
	visible: false,
});

const importOmsDialog = reactive<DialogOption>({
	title: "OMS原始单据导入",
	visible: false,
});

const deleteDialog = reactive<DialogOption>({
	title: "删除单据",
	visible: false,
});
/**
 * 导入选择的平台
 */
// const importPlatForm = ref<string>();
// const importOrderType = ref<string>();
// const storeId = ref<number>();
const storeGroup = ref<[]>([]);
const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const importParams = reactive<ImportVO>({});
const importColumnParams = reactive<ColumnImportVO>({});
const importOmsParams = reactive<any>({});

const rules = reactive({
  importPlatForm: [{ required: true, message: "请选择平台", trigger: "change" }],
  storeId: [{ required: true, message: "请选择店铺", trigger: "change" }],
  importOrderType: [{ required: true, message: "请选择单据类型", trigger: "change" }],
});

const columnRules = reactive({
	platformKey: [{ required: true, message: "请选择平台", trigger: "change" }],
	type: [{ required: true, message: "请选择单据类型", trigger: "change" }],
});

const omsRules = reactive({
	storeCode: [{ required: true, message: "请选择店铺", trigger: "change" }],
	type: [{ required: true, message: "请选择单据类型", trigger: "change" }],
});

/** 打开导入弹窗 */
async function openImportDialog() {
  importParams.importPlatForm = undefined
  importParams.storeId = undefined
  importParams.importOrderType = undefined
  importDialog.visible = true;
}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: UploadFile) {
	if (file.size !== undefined) {
		if (file.size > 20*1024*1024) {
			ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			return false
		}
	}
  if (!/\.(xlsx|xls|XLSX|XLS|csv|CSV)$/.test(file.name)) {
    ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
    excelFile.value = undefined;
    excelFilelist.value = [];
    return false;
  }
  excelFile.value = file.raw;
}

/** 导入用户提交 */
function handleBillImport() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}
  sourceRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (importParams.importPlatForm && importParams.storeId && importParams.importOrderType) {
        const importLoading = ElLoading.service({
          lock: true,
          text: '导入中...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
				const platformAndType = importParams.importPlatForm + '_' + importParams.importOrderType
        importBill(platformAndType, importParams.storeId, excelFile.value).then((response) => {
          ElMessage.success(response.data);
          closeImportDialog();
        }).finally(() => {
          importLoading.close()
        });
      }
    }
  });
}

/**  关闭导入弹窗 */
function closeImportDialog() {
  importDialog.visible = false;
  excelFile.value = undefined;
  excelFilelist.value = [];
}

function getStoreList() {
  if (importParams.importPlatForm) {
    getByStoreKey(importParams.importPlatForm).then((response) => {
      storeList.value = response.data;
      if (storeList.value !== undefined && storeList.value.length > 0 && storeList.value[0] !== undefined) {
        importParams.storeId = storeList.value[0].id
      }else{
        importParams.storeId = undefined
      }
    });
  }
}

/** 打开导入平台字段弹窗 */
async function openImportColumnDialog() {
	importColumnParams.platformKey = undefined
	importColumnParams.type = undefined
	importColumnDialog.visible = true;
}

/** 导入平台字段 */
function handleImportColumn() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}
	columnFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			if (importColumnParams.platformKey && importColumnParams.type) {
				const importLoading = ElLoading.service({
					lock: true,
					text: '导入中...',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				importColumn(importColumnParams.platformKey, importColumnParams.type, excelFile.value).then((response) => {
					ElMessage.success('导入成功');
					closeImportColumnDialog();
				}).finally(() => {
					importLoading.close()
				});
			}
		}
	});
}

/**  关闭导入弹窗 */
function closeImportColumnDialog() {
	importColumnDialog.visible = false;
	excelFile.value = undefined;
	excelFilelist.value = [];
}

function changePlatform() {
  getStoreList()
}

async function openDeleteDialog() {
	deleteDialog.visible = true;
}

function closeDeleteDialog() {
	deleteDialog.visible = false;
}

function handleSubmitDelete() {
	if (deleteMonthValue.value) {
	  const deleteLoading = ElLoading.service({
		  lock: true,
		  text: '删除中...',
		  background: 'rgba(0, 0, 0, 0.7)',
	  })
	  deleteParams.month = deleteMonthValue.value
	  deleteData(deleteParams).then((response) => {
		  ElMessage.success('删除完成');
		  closeDeleteDialog();
	  }).finally(() => {
		  deleteLoading.close()
	  });
	}
}

/** 打开导入OMS原始单据弹窗 */
async function openImportOmsDialog() {
	importOmsParams.type = undefined
	importOmsDialog.visible = true;
	getGroupStore()
}

/** 导入OMS原始单据 */
function handleImportOms() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}
	omsFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			if (importOmsParams.type) {
				const importLoading = ElLoading.service({
					lock: true,
					text: '导入中...',
					background: 'rgba(0, 0, 0, 0.7)',
				})
		  	importOmsData(importOmsParams.storeCode, importOmsParams.type, excelFile.value).then((response) => {
					ElMessage.success('导入成功');
					closeImportOmsDialog();
				}).finally(() => {
					importLoading.close()
				});
			}
		}
	});
}

function getGroupStore() {
	listAll().then((response) => {
		storeGroup.value = []
		const group_store = lodash.groupBy(response.data, 'storeKeyName');
		for (let key in group_store) {
			storeGroup.value.push({'label': key, 'options': group_store[key]})
		}
	})
}

/**  关闭导入弹窗 */
function closeImportOmsDialog() {
	importOmsDialog.visible = false;
	excelFile.value = undefined;
	excelFilelist.value = [];
}

</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :inline="true">
        <el-form-item style="display: none;">
          <el-button @click="openImportDialog" v-hasPerm="['sys:sourceOrder:import']">导入原始单据</el-button>
        </el-form-item>
        <el-form-item style="display: none;">
          <el-button>导入手工单</el-button>
        </el-form-item>
		  <el-form-item style="display: none;">
			  <el-button @click="openImportColumnDialog">平台字段导入</el-button>
		  </el-form-item>
		  <el-form-item>
			  <el-button @click="openImportOmsDialog">OMS原始单据导入</el-button>
		  </el-form-item>
		  <el-form-item style="display: none;">
			  <el-button @click="openDeleteDialog">删除单据</el-button>
		  </el-form-item>
      </el-form>
    </div>

    <!-- 导入原始单据弹窗 -->
    <el-dialog
      v-model="importDialog.visible"
      :title="importDialog.title"
      width="600px"
      append-to-body
	  :close-on-click-modal="false"
      @close="closeImportDialog"
    >
      <el-form ref="sourceRef" :rules="rules" :model="importParams" label-width="80px">
		  <el-form-item label="平台" prop="importPlatForm">
			  <dictionary v-model="importParams.importPlatForm" type-code="platform" @change="changePlatform" />
		  </el-form-item>
        <el-form-item label="店铺" prop="storeId">
          <el-select class="yz-el-select" v-model="importParams.storeId" placeholder="请选择">
            <el-option
                    v-for="item in storeList"
                    :key="item.id"
                    :label="item.commercePlatformStoreName"
                    :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单据类型" prop="importOrderType">
          <dictionary v-model="importParams.importOrderType" type-code="orderType" />
        </el-form-item>
        <el-form-item label="Excel">
          <el-upload
            class="upload-demo"
            action=""
            drag
            :auto-upload="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, .csv"
            :file-list="excelFilelist"
            :on-change="handleExcelChange"
            :limit="1"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">xls/xlsx/csv files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleBillImport">确 定</el-button>
          <el-button @click="closeImportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

	  <!-- 导入平台字段弹窗 -->
	  <el-dialog
			  v-model="importColumnDialog.visible"
			  :title="importColumnDialog.title"
			  width="600px"
			  append-to-body
			  :close-on-click-modal="false"
			  @close="closeImportColumnDialog"
	  >
		  <el-form ref="columnFormRef" :rules="columnRules" :model="importColumnParams" label-width="80px">
			  <el-form-item label="平台" prop="platformKey">
				  <dictionary v-model="importColumnParams.platformKey" type-code="platform" @change="changePlatform" />
			  </el-form-item>
			  <el-form-item label="单据类型" prop="type">
				  <dictionary v-model="importColumnParams.type" type-code="orderType" />
			  </el-form-item>
			  <el-form-item label="Excel">
				  <el-upload
						  class="upload-demo"
						  action=""
						  drag
						  :auto-upload="false"
						  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, .csv"
						  :file-list="excelFilelist"
						  :on-change="handleExcelChange"
						  :limit="1"
				  >
					  <el-icon class="el-icon--upload">
						  <i-ep-upload-filled />
					  </el-icon>
					  <div class="el-upload__text">
						  将文件拖到此处，或
						  <em>点击上传</em>
					  </div>
					  <template #tip>
						  <div class="el-upload__tip">xls/xlsx/csv files</div>
					  </template>
				  </el-upload>
			  </el-form-item>
		  </el-form>
		  <template #footer>
			  <div class="dialog-footer">
				  <el-button type="primary" @click="handleImportColumn">确 定</el-button>
				  <el-button @click="closeImportColumnDialog">取 消</el-button>
			  </div>
		  </template>
	  </el-dialog>

	  <!-- 导入OMS原始单据弹窗 -->
	  <el-dialog
			  v-model="importOmsDialog.visible"
			  :title="importOmsDialog.title"
			  width="600px"
			  append-to-body
			  :close-on-click-modal="false"
			  @close="closeImportOmsDialog"
	  >
		  <el-form ref="omsFormRef" :rules="omsRules" :model="importOmsParams" label-width="80px">
				<el-form-item label="店铺" prop="storeCode">
					<el-select class="yz-el-select" v-model="importOmsParams.storeCode" filterable placeholder="请选择店铺" style="width: 200px">
						<el-option-group
								v-for="group in storeGroup"
								:key="group.label"
								:label="group.label"
						>
							<el-option
									v-for="item in group.options"
									:key="item.id"
									:label="item.commercePlatformStoreName"
									:value="item.commercePlatformStoreCode"
							/>
						</el-option-group>
					</el-select>
				</el-form-item>
			  <el-form-item label="单据类型" prop="type">
					<el-select
							v-model="importOmsParams.type"
							placeholder="单据类型"
							:clearable="false"
							class="yz-el-select"
					>
						<el-option label="销售订单" value="0" />
						<el-option label="售后单" value="1" />
					</el-select>
			  </el-form-item>
			  <el-form-item label="Excel">
				  <el-upload
						  class="upload-demo"
						  action=""
						  drag
						  :auto-upload="false"
						  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, .csv"
						  :file-list="excelFilelist"
						  :on-change="handleExcelChange"
						  :limit="1"
				  >
					  <el-icon class="el-icon--upload">
						  <i-ep-upload-filled />
					  </el-icon>
					  <div class="el-upload__text">
						  将文件拖到此处，或
						  <em>点击上传</em>
					  </div>
					  <template #tip>
						  <div class="el-upload__tip">xls/xlsx/csv files</div>
					  </template>
				  </el-upload>
			  </el-form-item>
		  </el-form>
		  <template #footer>
			  <div class="dialog-footer">
				  <el-button type="primary" @click="handleImportOms">确 定</el-button>
				  <el-button @click="closeImportOmsDialog">取 消</el-button>
			  </div>
		  </template>
	  </el-dialog>

		<!--删除单据弹窗-->
	  <el-dialog
			  v-model="deleteDialog.visible"
			  :title="deleteDialog.title"
			  width="500px"
			  :close-on-click-modal="false"
			  @close="closeDeleteDialog"
	  >
		  <el-form
				  ref="dataFormRef"
				  label-width="150px"
		  >
			  <el-date-picker
					  v-model="deleteMonthValue"
					  type="month"
					  value-format="YYYYMM"
					  :editable="false"
					  :clearable="false"
					  placeholder="选择账单月份"
			  />
		  </el-form>
		  <template #footer>
			  <div class="dialog-footer">
				  <el-button type="primary" @click="handleSubmitDelete">确 定</el-button>
				  <el-button @click="closeDeleteDialog">取 消</el-button>
			  </div>
		  </template>
	  </el-dialog>
  </div>
</template>
